package cn.com.anypay.manager.payment.channel.channeltest2;

import cn.com.anypay.manager.payment.config.ChannelConfig;
import cn.com.anypay.manager.payment.config.TestChannelConfig;
import cn.com.anypay.manager.payment.core.AbstractPaymentChannelTemplate;
import cn.com.anypay.manager.payment.core.PaymentException;
import cn.com.anypay.manager.payment.core.IPaymentChannelImplementation;
import cn.com.anypay.manager.payment.core.ImplementationMetadata;
import cn.com.anypay.manager.payment.dto.*;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * 测试渠道2 - 支付渠道策略实现
 *
 * 演示支付渠道抽象框架的使用，模拟不同类型的支付渠道特性
 * 使用策略模式，实现具体的支付渠道策略
 *
 * @author AnyPay Team
 * @version 1.0
 * @since 2025-07-05
 */
@Component("channelTest2DefaultPaymentChannelStrategy")
@ImplementationMetadata(
    channelId = ChannelTest2PaymentChannelStrategy.CHANNEL_ID,
    implementationId = ChannelTest2PaymentChannelStrategy.IMPLEMENTATION_ID,
    implementationName = ChannelTest2PaymentChannelStrategy.IMPLEMENTATION_NAME,
    version = "1.0.0",
    description = "测试渠道2的默认实现"
)
public class ChannelTest2PaymentChannelStrategy extends AbstractPaymentChannelTemplate implements IPaymentChannelImplementation {

    public static final String CHANNEL_ID = "channeltest2";
    public static final String IMPLEMENTATION_ID = "default";
    public static final String CHANNEL_NAME = "测试渠道2";
    public static final String IMPLEMENTATION_NAME = "测试渠道2-默认实现";
    // 移除静态数组，改用从ProductFactory动态获取

    public ChannelTest2PaymentChannelStrategy() {
        super();
        // 创建默认配置
        TestChannelConfig config = new TestChannelConfig(CHANNEL_ID, CHANNEL_NAME);
        config.setConfigParam("successRate", 90); // 不同的成功率
        config.setConfigParam("processingTime", 500); // 不同的处理时间
        config.setConfigParam("supportRefund", true); // 支持退款
        this.channelConfig = config;
    }

    public ChannelTest2PaymentChannelStrategy(ChannelConfig channelConfig) {
        super(channelConfig);
    }

    @Override
    public String getChannelId() {
        return CHANNEL_ID;
    }

    @Override
    public String getChannelName() {
        return CHANNEL_NAME;
    }

    @Override
    public String getImplementationId() {
        return IMPLEMENTATION_ID;
    }

    @Override
    public String[] getSupportedPayProducts() {
        // 使用父类的动态获取方法
        return getSupportedPayProductsFromFactory();
    }

    @Override
    public String getConfigTemplate() {
        return "{\n" +
                "  \"timeout\": 60000,\n" +
                "  \"retryCount\": 5,\n" +
                "  \"logLevel\": \"DEBUG\",\n" +
                "  \"mockMode\": true,\n" +
                "  \"successRate\": 90,\n" +
                "  \"processingTime\": 500,\n" +
                "  \"supportRefund\": true\n" +
                "}";
    }

    @Override
    protected void doInitialize() throws PaymentException {
        logger.debug("=== ChannelTest2 Default实现 初始化开始 ===");
        logger.debug("渠道ID: {}", getChannelId());
        logger.debug("渠道名称: {}", getChannelName());
        logger.debug("实现ID: {}", getImplementationId());
        logger.debug("支持的支付产品: APP, WEB, QR");

        // 模拟更复杂的初始化过程
        try {
            logger.debug("正在加载渠道配置...");
            Thread.sleep(200); // 模拟配置加载

            logger.debug("正在建立连接...");
            Thread.sleep(150); // 模拟连接建立

            logger.debug("正在验证权限...");
            Thread.sleep(100); // 模拟权限验证

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        logger.debug("=== ChannelTest2 Default实现 初始化完成 ===");
        logger.debug("Initializing channel: {}", getChannelId());
        logger.debug("Channel {} initialized successfully", getChannelId());
    }

    @Override
    protected void doDestroy() {
        logger.debug("=== ChannelTest2 Default实现 销毁开始 ===");
        logger.debug("关闭连接...");

        // 模拟销毁过程
        try {
            Thread.sleep(80); // 模拟销毁耗时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        logger.debug("=== ChannelTest2 Default实现 销毁完成 ===");
    }

    @Override
    protected PaymentResultDTO doCreatePayment(PaymentRequestDTO request) throws PaymentException {
        logger.debug("=== ChannelTest2 Default实现 创建支付 ===");
        logger.debug("商户订单号: {}", request.getMerchantOrderId());
        logger.debug("支付金额: {} {}", request.getAmount(), request.getCurrency());
        logger.debug("商品描述: {}", request.getSubject());
        logger.debug("支付产品: {}", request.getPayProduct());

        // 获取处理时间配置
        Integer processingTime = channelConfig.getConfigParamAsInteger("processingTime");
        if (processingTime == null) {
            processingTime = 500;
        }

        // 模拟支付创建过程
        try {
            Thread.sleep(processingTime); // 模拟API调用耗时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 模拟成功率配置
        Integer successRate = channelConfig.getConfigParamAsInteger("successRate");
        if (successRate == null) {
            successRate = 90;
        }

        // 根据成功率决定是否成功
        boolean success = Math.random() * 100 < successRate;

        if (!success) {
            logger.error("支付创建失败 - 模拟失败场景");
            throw new PaymentException("CREATE_FAILED", "网络超时，请稍后重试", getChannelId());
        }

        // 创建成功结果
        String channelOrderId = "TEST2_DEFAULT_" + UUID.randomUUID().toString().replace("-", "");

        PaymentResultDTO result = PaymentResultDTO.success(request.getMerchantOrderId(), channelOrderId);
        result.setAmount(request.getAmount());
        result.setStatus(PaymentStatusDTO.PENDING);
        result.setCreateTime(new Date());

        // 根据支付产品设置不同的响应数据
        switch (request.getPayProduct()) {
            case "APP":
                result.setHtmlCode("{\"appData\":\"" + channelOrderId + "\",\"scheme\":\"testapp://pay\"}");
                logger.debug("生成APP支付数据");
                break;
            case "WEB":
                result.setPayUrl("https://test2.payment.com/web?token=" + channelOrderId);
                logger.debug("生成WEB支付链接: {}", result.getPayUrl());
                break;
            case "QR":
                result.setQrCode("https://test2.payment.com/qr/" + channelOrderId);
                logger.debug("生成二维码支付: {}", result.getQrCode());
                break;
        }

        logger.debug("支付创建成功，渠道订单号: {}", channelOrderId);
        return result;
    }

    @Override
    protected QueryResultDTO doQueryPayment(QueryRequestDTO request) throws PaymentException {
        logger.debug("=== ChannelTest2 Default实现 查询支付 ===");
        logger.debug("商户订单号: {}", request.getMerchantOrderId());
        logger.debug("渠道订单号: {}", request.getChannelOrderId());

        // 模拟查询过程
        try {
            Thread.sleep(300); // 模拟API调用耗时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 模拟查询结果
        QueryResultDTO result = QueryResultDTO.success();
        result.setMerchantOrderId(request.getMerchantOrderId());
        result.setChannelOrderId(request.getChannelOrderId());

        // 随机生成支付状态 (不同的概率分布)
        double random = Math.random();
        if (random < 0.6) {
            result.setStatus(PaymentStatusDTO.SUCCESS);
            result.setPayTime(new Date());
            result.setPaidAmount(new BigDecimal("200.00"));
            logger.debug("支付状态: 成功");
        } else if (random < 0.8) {
            result.setStatus(PaymentStatusDTO.PENDING);
            logger.debug("支付状态: 处理中");
        } else {
            result.setStatus(PaymentStatusDTO.FAILED);
            result.setErrorCode("PAYMENT_FAILED");
            result.setErrorMessage("支付失败");
            logger.debug("支付状态: 失败");
        }

        result.setAmount(new BigDecimal("200.00"));
        result.setCurrency("CNY");
        result.setCreateTime(new Date());

        logger.debug("查询完成，状态: {}", result.getStatus());
        return result;
    }

    @Override
    protected boolean doClosePayment(String orderId) throws PaymentException {
        logger.debug("=== ChannelTest2 Default实现 关闭支付 ===");
        logger.debug("订单号: {}", orderId);

        // 模拟关闭过程
        try {
            Thread.sleep(200); // 模拟API调用耗时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 模拟关闭结果 (85%成功率)
        boolean success = Math.random() < 0.85;
        logger.debug("关闭支付{}: {}", success ? "成功" : "失败", orderId);
        return success;
    }

    @Override
    protected boolean doVerifyCallback(String data) throws PaymentException {
        logger.debug("=== ChannelTest2 Default实现 验证回调 ===");
        logger.debug("回调数据长度: {}", data.length());

        // 模拟签名验证
        if (data.contains("sign=") && data.contains("TEST2_DEFAULT_")) {
            logger.debug("回调验证成功");
            return true;
        } else {
            logger.warn("回调验证失败: 缺少签名或订单标识");
            return false;
        }
    }

    @Override
    protected PaymentResultDTO doProcessCallback(String data) throws PaymentException {
        logger.debug("=== ChannelTest2 Default实现 处理回调 ===");

        // 解析回调数据
        PaymentResultDTO result = new PaymentResultDTO();
        result.setSuccess(true);
        result.setMerchantOrderId("CALLBACK_ORDER_" + System.currentTimeMillis());
        result.setChannelOrderId("TEST2_DEFAULT_" + UUID.randomUUID().toString().replace("-", ""));
        result.setStatus(PaymentStatusDTO.SUCCESS);
        result.setAmount(new BigDecimal("200.00"));
        result.setPayTime(new Date());
        result.setRawData(data);

        logger.debug("回调处理完成");
        return result;
    }

    @Override
    protected boolean doValidateConfig(String config) {
        logger.debug("=== ChannelTest2 Default实现 验证配置 ===");

        if (config == null || config.trim().isEmpty()) {
            logger.error("配置为空");
            return false;
        }

        // 简单的配置验证
        if (config.contains("timeout") && config.contains("retryCount")) {
            logger.debug("配置验证通过");
            return true;
        } else {
            logger.error("配置验证失败: 缺少必要参数");
            return false;
        }
    }

    @Override
    public void registerProducts(cn.com.anypay.manager.payment.factory.PaymentProductFactory productFactory) {
        logger.debug("=== ChannelTest2 注册支付产品 ===");

        try {
            // 注册APP支付产品
            cn.com.anypay.manager.payment.channel.channeltest2.products.AppPaymentProductStrategy appProduct =
                new cn.com.anypay.manager.payment.channel.channeltest2.products.AppPaymentProductStrategy();
            productFactory.registerProductByChannel(CHANNEL_ID, IMPLEMENTATION_ID, "APP", appProduct);

            // 注册WEB支付产品
            cn.com.anypay.manager.payment.channel.channeltest2.products.WebPaymentProductStrategy webProduct =
                new cn.com.anypay.manager.payment.channel.channeltest2.products.WebPaymentProductStrategy();
            productFactory.registerProductByChannel(CHANNEL_ID, IMPLEMENTATION_ID, "WEB", webProduct);

            // 注册QR支付产品
            cn.com.anypay.manager.payment.channel.channeltest2.products.QRPaymentProductStrategy qrProduct =
                new cn.com.anypay.manager.payment.channel.channeltest2.products.QRPaymentProductStrategy();
            productFactory.registerProductByChannel(CHANNEL_ID, IMPLEMENTATION_ID, "QR", qrProduct);

            logger.debug("ChannelTest2 支付产品注册完成");
        } catch (Exception e) {
            logger.error("ChannelTest2 注册支付产品失败", e);
        }
    }
}